package com.linkai.基础._01_copy;

import com.linkai.JVM.Student;
import com.sun.xml.internal.ws.server.ServerRtException;

/**
 * @Description: 深拷贝
 *                深拷贝需要重写
 *                深拷贝把要复制的对象所引用的对象都复制了一遍。
 * @Author: 林凯
 * @Date: 2021/10/29 23:33
 */
public class _04_DeepCopy {
    public static void main(String[] args) throws CloneNotSupportedException {
        Teacher4 t1 = new Teacher4("JackLin", 21);
        Student4 s1 = new Student4("s_jacklin", 18, t1);
        Student4 s2 = (Student4) s1.clone();

        // 深拷贝，重写了 clone() 方法，对象内部的对象也会在堆中拷贝一份；所以这4个对象都不相同
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s1.getTeacher4());
        System.out.println(s2.getTeacher4());
        /*
            com.linkai.基础._01_copy.Student4@74a14482
            com.linkai.基础._01_copy.Student4@1540e19d
            com.linkai.基础._01_copy.Teacher4@677327b6
            com.linkai.基础._01_copy.Teacher4@14ae5a5

        * */
    }
}


class Teacher4 implements Cloneable {
    private String name;
    private int age;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public Teacher4(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

// 深拷贝需要重写 clone() 方法
// 在 clone()(
class Student4 implements Cloneable {
    private String name;
    private int age;
    private Teacher4 teacher4;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        // 浅复制
//        return super.clone();
        // 深复制
        Student4 student4 = (Student4) super.clone();
        //  还需要现在将Teacher对象复制一份并重新set进来
        student4.setTeacher4((Teacher4) student4.getTeacher4().clone());
        return student4;
    }

    public Student4(String name, int age, Teacher4 teacher4) {
        this.name = name;
        this.age = age;
        this.teacher4 = teacher4;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Teacher4 getTeacher4() {
        return teacher4;
    }

    public void setTeacher4(Teacher4 teacher4) {
        this.teacher4 = teacher4;
    }
}